const fs = require('fs')
let Student = require('./student')

const express = require('express')

var router = express.Router()

router.get('/', (req, res) => {
	Student.find((err, students) => {
		if(err){
			return res.status(500).send('Server error')
		}
		res.render('index.html', {
			students: students
		})
	})
})

router.get('/add', (req, res) => {
	 res.render('new.html',{ stu: {name:''}})
})

router.post('/save', (req, res) => {
	 Student.save(req.body, err => {
		 if(err){
			 return res.status(500).send('Server error')
		 }
		 res.redirect('/')	
	 })
})

router.get('/edit', (req, res) => {
	Student.edit(req.query.id, (err,stu) => {
		if(err){
			return res.status(500).send('Server error')
		}
		res.render('new.html', {
			stu: stu
		})
	})
})

router.post('/edit', (req, res) => {
	Student.editSave(req.body, err => {
		if(err){
			return res.status(500).send('Server error')
		}
		console.log(req.body)
		res.redirect('/')	
	})
})

router.get('/del', (req, res) => {
	Student.del(req.query.id, err => {
		if(err){
			return res.status(500).send('Server error')
		}
		res.redirect('/')	
	})
})





module.exports = router